﻿using System;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Multi_protocol_upper_computer.Infrastructure;
using Multi_protocol_upper_computer.Services;
using Multi_protocol_upper_computer.ViewModels;
using Multi_protocol_upper_computer.Views;
using Prism.Navigation.Regions;

namespace Multi_protocol_upper_computer
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private IHost _host;
        private IServiceProvider _serviceProvider;

        protected override void OnStartup(StartupEventArgs e)
        {
            // 配置依赖注入
            ConfigureDependencyInjection();
            
            // 配置NLog
            ConfigureLogging();
            
            base.OnStartup(e);
            
            // 记录启动日志
            try
            {
                var loggingService = _serviceProvider.GetService<ILoggingService>();
                loggingService?.LogInfo("多协议上位机应用程序已启动");
            }
            catch
            {
                // 忽略日志配置错误
            }

            // 创建并显示主窗口
            var mainWindow = _serviceProvider.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            try
            {
                var loggingService = _serviceProvider?.GetService<ILoggingService>();
                loggingService?.LogInfo("应用程序正在退出");
            }
            catch
            {
                // 忽略日志配置错误
            }
            
            // 释放Host资源
            _host?.Dispose();
            
            base.OnExit(e);
        }

        /// <summary>
        /// 配置依赖注入容器
        /// </summary>
        private void ConfigureDependencyInjection()
        {
            var hostBuilder = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    // 注册基础设施服务
                    services.AddSingleton<ProcessMonitor>();
                    services.AddSingleton<ILoggingService, LoggingService>();
                    
                    // 注册Prism服务
                    services.AddSingleton<IRegionManager, RegionManager>();
                    
                    // 注册通信服务
                    services.AddTransient<SerialCommunicationService>();
                    services.AddTransient<ModbusCommunicationService>();
                    services.AddTransient<TcpUdpCommunicationService>();
                    
                    // 注册其他服务
                    services.AddSingleton<EncryptionService>();
                    services.AddSingleton<DataService>();
                    services.AddSingleton<SafeQueueService>();
                    
                    // 注册ViewModels
                    services.AddTransient<MainViewModel>();
                    services.AddTransient<DataCollectionViewModel>();
                    services.AddTransient<CommunicationViewModel>();
                    services.AddTransient<LogViewModel>();
                    
                    // 注册Views
                    services.AddTransient<MainWindow>();
                    services.AddTransient<MainView>();
                    services.AddTransient<DataCollectionView>();
                    services.AddTransient<CommunicationView>();
                    services.AddTransient<LogView>();
                });

            _host = hostBuilder.Build();
            _serviceProvider = _host.Services;
        }

        /// <summary>
        /// 配置日志
        /// </summary>
        private void ConfigureLogging()
        {
            try
            {
                var config = new NLog.Config.LoggingConfiguration();
                
                // 文件日志目标
                var fileTarget = new NLog.Targets.FileTarget("fileTarget")
                {
                    FileName = "${basedir}/logs/${shortdate}.log",
                    Layout = "${longdate} ${uppercase:${level}} ${logger} ${message} ${exception:format=tostring}"
                };
                // 异步文件日志目标
                var asyncFileTarget = new NLog.Targets.FileTarget("asyncFileTarget")
                {
                    FileName = "${basedir}/logs/${shortdate}_async.log",
                    Layout = "${longdate} ${uppercase:${level}} ${logger} ${message} ${exception:format=tostring}"
                };
                // 控制台日志目标
                var consoleTarget = new NLog.Targets.ConsoleTarget("consoleTarget")
                {
                    Layout = "${time} ${uppercase:${level}} ${message}"
                };

                // 添加规则
                config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, fileTarget);
                config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, consoleTarget);
                config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, asyncFileTarget);

                NLog.LogManager.Configuration = config;
            }
            catch
            {
                // 如果日志配置失败，继续运行应用程序
            }
        }

        /// <summary>
        /// 获取服务实例的公共方法
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        /// <returns>服务实例</returns>
        public static T GetService<T>() where T : class
        {
            var app = Current as App;
            return app?._serviceProvider?.GetService<T>();
        }
    }
}
